package com.example.healthmanagement.ui.activity;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.example.healthmanagement.R;
import com.example.healthmanagement.adapter.MenuAdapter;
import com.example.healthmanagement.bean.Menu;
import com.example.healthmanagement.databinding.DialogEditMenuBinding;
import com.example.healthmanagement.util.MySqliteOpenHelper;
import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class MenuManagerActivity extends AppCompatActivity {

    MySqliteOpenHelper helper = null;
    private TabLayout tabTitle;
    private RecyclerView rvList;
    private MenuAdapter menuAdapter;
    private LinearLayout llEmpty;
    private String[] state = {"0", "1", "2", "3", "4"};
    private String[] title = {"早餐", "午餐", "下午茶", "晚餐", "夜宵"};
    private String typeId = "0";
    private List<Menu> menuList;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_menu);
        findViewById(R.id.rl_title).setVisibility(View.VISIBLE);
        findViewById(R.id.iv_add).setOnClickListener(v -> {
            showAddDialog();
        });
        helper = new MySqliteOpenHelper(this);
        tabTitle = findViewById(R.id.tab_title);
        rvList = findViewById(R.id.rv_menu_list);
        llEmpty = findViewById(R.id.ll_empty);
        initView();
    }

    private void showAddDialog() {
        DialogEditMenuBinding binding = DialogEditMenuBinding.inflate(getLayoutInflater());

        AlertDialog show = new AlertDialog.Builder(this).setView(binding.getRoot()).show();
        binding.btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                show.dismiss();
            }
        });
        binding.btnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = binding.etUrl.getText().toString();
                String img = binding.etImage.getText().toString();
                String title = binding.etName.getText().toString();
                if (url.isEmpty() || img.isEmpty() || title.isEmpty()) {
                    return;
                }
                Menu menu = new Menu();
                menu.setUrl(url);
                menu.setImg(img);
                menu.setTitle(title);
                menu.setTypeId(Integer.parseInt(typeId));
                SQLiteDatabase writableDatabase = helper.getWritableDatabase();
                writableDatabase.insert("menu", null, menu.toContentValues());
                show.dismiss();
                loadData();
            }
        });
    }

    /**
     * 初始化页面
     */
    private void initView() {
        tabTitle.setTabMode(TabLayout.MODE_SCROLLABLE);
        //设置tablayout距离上下左右的距离
        //tab_title.setPadding(20,20,20,20);

        //为TabLayout添加tab名称
        for (int i = 0; i < title.length; i++) {
            tabTitle.addTab(tabTitle.newTab().setText(title[i]));
        }
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        //=1.2、设置为垂直排列，用setOrientation方法设置(默认为垂直布局)
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //=1.3、设置recyclerView的布局管理器
        rvList.setLayoutManager(layoutManager);
        //==2、实例化适配器
        //=2.1、初始化适配器
        menuAdapter = new MenuAdapter();
        //=2.3、设置recyclerView的适配器
        rvList.setAdapter(menuAdapter);
        loadData();
        menuAdapter.setItemListener(new MenuAdapter.ItemListener() {
            @Override
            public void ItemClick(Menu menu) {
                new AlertDialog.Builder(MenuManagerActivity.this).setItems(new CharSequence[]{"查看详情", "编辑", "删除"}, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            Intent intent = new Intent(MenuManagerActivity.this, MenuDetailActivity.class);
                            intent.putExtra("url", menu.getUrl());
                            startActivity(intent);
                        } else if (which == 1) {
                            showEditDialog(menu);
                        } else if (which == 2) {
                            SQLiteDatabase writableDatabase = helper.getWritableDatabase();
                            writableDatabase.delete("menu", "id = ?", new String[]{menu.getId() + ""});
                            loadData();
                        }
                    }
                }).show();
            }
        });
        tabTitle.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                typeId = state[tab.getPosition()];
                loadData();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    private void showEditDialog(Menu menu) {
        DialogEditMenuBinding binding = DialogEditMenuBinding.inflate(getLayoutInflater());
        binding.etImage.setText(menu.getImg());
        binding.etName.setText(menu.getTitle());
        binding.etUrl.setText(menu.getUrl());
        AlertDialog show = new AlertDialog.Builder(this).setView(binding.getRoot()).show();
        binding.btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                show.dismiss();
            }
        });
        binding.btnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = binding.etUrl.getText().toString();
                String img = binding.etImage.getText().toString();
                String title = binding.etName.getText().toString();
                if (url.isEmpty() || img.isEmpty() || title.isEmpty()) {
                    return;
                }
                menu.setUrl(url);
                menu.setImg(img);
                menu.setTitle(title);
                SQLiteDatabase writableDatabase = helper.getWritableDatabase();
                writableDatabase.update("menu", menu.toContentValues(), "id = ?", new String[]{menu.getId() + ""});
                show.dismiss();
                loadData();
            }
        });
    }

    private void loadData() {
        menuList = new ArrayList<>();
        Menu menu = null;
        String sql = "select * from menu where typeId =" + typeId;
        SQLiteDatabase db = helper.getWritableDatabase();
        Cursor cursor = db.rawQuery(sql, null);
        if (cursor != null && cursor.getColumnCount() > 0) {
            while (cursor.moveToNext()) {
                Integer dbId = cursor.getInt(0);
                Integer typeId = cursor.getInt(1);
                String title = cursor.getString(2);
                String img = cursor.getString(3);
                String url = cursor.getString(4);
                menu = new Menu(dbId, typeId, title, img, url);
                menuList.add(menu);
            }
        }
        Collections.reverse(menuList);
        if (menuList != null && menuList.size() > 0) {
            rvList.setVisibility(View.VISIBLE);
            llEmpty.setVisibility(View.GONE);
            menuAdapter.addItem(menuList);
        } else {
            rvList.setVisibility(View.GONE);
            llEmpty.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        loadData();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == RESULT_OK) {
            loadData();//加载数据
        }
    }
}